<template>
  <div class="keyword pad">
    <div class="head">
      <span>知识关键字</span>
    </div>
    <el-form :model="keyWord" inline ref="keyword" :rules="rules" class="m-t-b">
      <el-form-item label="关键字名称" prop="keywordTitle">
        <el-input v-model="keyWord.keywordTitle" />
      </el-form-item>
      <el-form-item label="关联父级">
        <el-select v-model="keyWord.parentId" filterable>
          <el-option
            v-for="item in keyWordList"
            :key="item.keywordId"
            :value="item.keywordId"
            :label="item.keywordTitle"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 20px;">
        <el-button type="primary" :loading="isDoing" @click="saveKeyword">保存</el-button>
      </el-form-item>
    </el-form>

    <el-form inline>
      <el-form-item label="关键字类别" style="margin-left: 8px">
        <el-select
         v-model="selectParKeyWord"
         @change="ParentKeywordInput"
         placeholder="请选择关键字类别"
         clearable
         filterable
         style=" width: 200px;"
        >
          <el-option
            v-for="item in ParKeyWord"
            :key="item.keywordId"
            :label="item.keywordTitle"
            :value="item.keywordId">
          </el-option>
        </el-select>

        
      </el-form-item>

      <el-form-item label="选关键字">
        <el-select 
         v-model="selectChilKey"
         placeholder="选择关键字"
         clearable
         filterable
         style="margin-right: 20px"
        >
          <el-option
            v-for="item in inputsChildKeyWord"
            :key="item.keywordId"
            :label="item.keywordTitle"
            :value="item.keywordId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="修改关键字" :visible.sync="isShow">
      <el-input v-model="selectChilKeyTitle" placeholder="请输入内容" clearable></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="update ">确认修改</el-button>
      </div>
    </el-dialog>

    <div style="margin-top: 30px;">
      <div style="font-size: 20px;font-weight: bold;">关键字树结构</div>
      <el-tree
        class="m-t-b"
        :data="keyWordList"
        :props="defaultProps"
        @node-click="handleNodeClick"
        :default-expand-all="true"
      ></el-tree>
    </div>
  </div>
</template>
<script>
import { formatDate } from '../util';
import {
  addKeyWord,
  getAllKeyWords,
  getkeyWord,
  updateKeyWord,
} from '../api/version2'
export default {
  name: 'KeyWord',
  data () {
    return {
      loading: false,
      isDoing: false,
      isShow: false,
      selectParKeyWord: '',
      selectChilKeyTitle: '',
      selectChilKey: '',
      inputsChildKeyWord: [],
      ParKeyWord: [],
      kewords: [],
      keyWordList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      keyWord: {
        keywordTitle: '',
        parentId: ''
      },
      rules: {
        keywordTitle: [
          { required: true, message: '关键字不能为空', trigger: 'blur' }
        ]
      },
      rulesForm: {
        parentKeywordTitle: [
          {required: true,trigger: 'blur', message: "此项为必填项"},
        ],
        childrenKeyWordTitle: [
          {required: true, trigger: 'blur', message: '此项为必填项'}
        ]
      }
    }
  },
  methods: {
    fetchKeyWords () { // 查询所有关键字
      this.loading = true;
      getAllKeyWords()
      .then(res => {
        let list = res.data.data || [];
        list.forEach(item => {
          item.label = item.keywordTitle;
          item.children = []
        });
        this.formatTreeData(list);
        this.loading = false
      })
      .catch(e => {
        this.loading = false
      })
    },
    formatTreeData (list) { // 格式化树形数据
      let parents = list.filter(item => item.parentId == '0');
      parents.forEach(p => {
        list.forEach(item => {
          if (p.keywordId == item.parentId) {
            p.children.push(item)
          }
        })
      });
      parents.forEach(item => {
        item.label = `${item.label}(${item.children.length}个子类别)`
      });
      this.keyWordList = parents;
      this.kewords = parents;
    },
    handleNodeClick (row) { // 节点点击
      
    },
    saveKeyword () { // 保存关键字
      this.$refs.keyword.validate(valid => {
        if (valid) {
          this.isDoing = true;
          addKeyWord(this.keyWord.keywordTitle, this.keyWord.parentId || 0)
          .then(res => {
            this.$message.success('创建成功');
            this.fetchKeyWords();
            this.isDoing = false
          })
          .catch(e => {
            this.isDoing = false
          })
        } else {
          return false
        }
      })
    },
    

    // 获取父级关键字
    getParentId() {
      getkeyWord({
        parentId: '0',
      }).then(res => {
        let list = res.data.data;
        this.ParKeyWord = list;
      })
    },

    // 获取子级的关键字
    getChildKeywordId(parKeyId) {
      if(!this.selectParKeyWord) {
        this.inputsChildKeyWord = '';
      } else {
          getkeyWord({
          parentId: parKeyId,
        }).then(res => {
        this.inputsChildKeyWord = res.data.data;
      })
      }
    },

    // 选择父级关键字后，获取相应父级关键字的子级关键字
    ParentKeywordInput() {
      this.selectChilKey = '';
      this.getChildKeywordId(this.selectParKeyWord);
    },

    // 点击搜索按钮
    searchDetails() {
      this.isShow = true;
      if(this.selectChilKey) {
        for(let i = 0; i<this.inputsChildKeyWord.length; i++) {
          if(this.selectChilKey == this.inputsChildKeyWord[i].keywordId) {
            // console.log(this.inputsChildKeyWord[i].keywordTitle);
            this.selectChilKeyTitle = this.inputsChildKeyWord[i].keywordTitle;
          }
        }
      };
    },

    
    search() {
      if(!this.selectChilKey) {
        this.$message.error("关键字不能为空");
      } else {
        this.searchDetails();
      }
    },

    // 取消修改
    cancle() {
      this.isShow = false;
      this.selectParKeyWord = '';
      this.selectChilKey = '';
      this.selectChilKeyTitle = '';
      this.inputsChildKeyWord = [];
    },

    // 确认修改关键字
    update() {
      if(!this.selectChilKeyTitle){
        this.$message.error("请输入合法的关键字");
      } else {
        updateKeyWord({
        keywordTitle: this.selectChilKeyTitle,
        keywordId: this.selectChilKey,
      }).then(res => {
        // console.log(res);
        this.$message.success("修改成功");
        this.isShow = false;
        this.selectParKeyWord = '';
        this.selectChilKey = '';
        this.fetchKeyWords();
      })
      }
    },
  },
  created () {
    this.fetchKeyWords()
    this.getParentId();
  }
}
</script>
<style lang="scss">

</style>
